<template>
  <div class="addVisiting-container">
    <van-form label-align="left" @submit="onSubmit">
      <van-cell-group>
        <van-field name="radio" required label="拜访类型" :rules="[{ required: true, message: '请选择拜访类型' }]">
          <template #input>
            <van-radio-group v-model="selectVisitingType" direction="horizontal">
              <van-radio v-for="item in visitingTypeColumns" :name="item.value" :key="item.value"
                >{{ item.text }}
              </van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field
          v-model="visitingDate"
          is-link
          readonly
          name="datePicker"
          label="拜访日期"
          required
          disabled
          :rules="[{ required: true, message: '请选择拜访日期' }]"
        />
        <!--	      @click="showVisitingDatePicker = true"-->
        <!--        <van-popup v-model:show="showVisitingDatePicker" position="bottom">-->
        <!--          <van-datetime-picker-->
        <!--	          v-model="visitingDate"-->
        <!--            type="date"-->
        <!--            :formatter="formatter"-->
        <!--            @confirm="onConfirmVisitingDate"-->
        <!--            @cancel="showVisitingDatePicker = false"-->
        <!--          />-->
        <!--        </van-popup>-->
        <van-field v-model="visitingReason" name="拜访事由" label="拜访事由" type="textarea" placeholder="拜访事由" />
        <van-field v-model="visitingResult" type="textarea" name="拜访结果" label="拜访结果" placeholder="拜访结果" />
        <van-field
          v-model="relevanceClue.title"
          is-link
          readonly
          name="picker"
          label="关联商机"
          placeholder="点击选择关联商机"
          :required="selectVisitingType === 'PB'"
          :disabled="!!visitingId"
          :rules="selectVisitingType === 'PB' ? [{ required: true, message: '请选择关联商机' }] : []"
          @click="!visitingId ? handleOpenCluePicker() : ''"
        />
        <van-popup v-model:show="showCluePicker" position="bottom" style="max-height: 580px">
          <van-search
            v-model="clubeSearchkey"
            show-action
            placeholder="请输入搜索关键词"
            clear-trigger="always"
            @search="onSearch"
            @clear="onSearch"
          >
            <template #action>
              <div @click="onSearch">搜索</div>
            </template>
          </van-search>
          <van-radio-group v-model="relevanceClueId" @change="onConfirmClue">
            <van-cell-group>
              <van-cell
                v-for="(item, index) in clueColumns"
                :key="index"
                :title="item.title"
                clickable
                @click="relevanceClueId = item.id"
              >
                <template #right-icon>
                  <van-radio :name="item.id" />
                </template>
              </van-cell>
            </van-cell-group>
          </van-radio-group>
          <van-empty v-if="!clueColumns.length" image-size="100" description="暂无商机客户" />
        </van-popup>
        <van-field
          v-model="customerName"
          name="客户名称"
          label="客户名称"
          placeholder="客户名称"
          :required="selectVisitingType === 'MB'"
          :disabled="selectVisitingType === 'PB'"
          :rules="selectVisitingType === 'MB' ? [{ required: true, message: '请填写客户名称' }] : []"
        />
        <van-field
          v-model="customerAddress"
          name="客户地址"
          :required="selectVisitingType === 'MB'"
          label="客户地址"
          right-icon="location-o"
          placeholder="客户地址"
          @click-right-icon="getLocation"
          :rules="selectVisitingType === 'MB' ? [{ required: true, message: '请填写客户地址' }] : []"
        />
        <van-field v-model="linkman" name="联系人" label="联系人" placeholder="联系人" />
        <van-field v-model="linkmanPhone" name="联系电话" label="联系电话" placeholder="联系电话" />
        <van-field
          v-model="internalVisitor"
          name="内部陪访人"
          label="内部陪访人"
          placeholder="内部陪访人"
          required
          :rules="[{ required: true, message: '请先填写内部陪访人' }]"
        />
        <van-field v-model="otherVisitor" name="其他陪访人" label="其他陪访人" placeholder="其他陪访人" />
        <!--        <van-field-->
        <!--          v-model="areaResult"-->
        <!--          is-link-->
        <!--          readonly-->
        <!--          required-->
        <!--          name="area"-->
        <!--          label="地区选择"-->
        <!--          placeholder="点击选择省市区"-->
        <!--          :rules="[{ required: true, message: '请选择地区' }]"-->
        <!--          @click="showArea = true"-->
        <!--        />-->
        <!--        <van-popup v-model:show="showArea" position="bottom">-->
        <!--          <van-area :area-list="areaList" @confirm="onConfirmArea" @cancel="showArea = false" />-->
        <!--        </van-popup>-->
        <van-field
          v-model="areaResult"
          name="区域"
          label="区域"
          required
          placeholder="区域"
          :rules="[{ required: true, message: '请填写区域' }]"
        />
        <van-field
          v-model="cityName"
          name="城市"
          label="城市"
          required
          placeholder="城市"
          :rules="[{ required: true, message: '请填写城市' }]"
        />
        <van-field name="uploader" label="图片上传" required :rules="[{ required: true, message: '请先上传图片' }]">
          <template #input>
            <water-mark-uploader
              :files="visitingFile"
              @beforeRead="beforeRead"
              @afterRead="afterRead"
              @deleteFile="deleteVisitingFile"
            />
          </template>
        </van-field>
        <van-field v-model="remark" type="textarea" name="备注" label="备注" placeholder="备注" />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit"> 提交 </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { onMounted, reactive, toRefs } from 'vue'
import { getDictionary } from '@/api/dictionary.js'
import { getRelevanceClue, addBusinessVisiting, getBusinessVisiting } from '@/api/businessOpportunity.js'
import { areaList } from '@/utils/area.js'
import { formatter, formatterDate } from '@/utils/index.js'
import WaterMarkUploader from '@/components/WaterMarkUploader.vue'
import { useRouter, useRoute } from 'vue-router'
import request from '@/utils/request.js'
import { Toast } from 'vant'
import * as ww from '@wecom/jssdk'
import { getSign } from '@/utils/jssdk'

export default {
  components: {
    WaterMarkUploader
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const state = reactive({
      visitingId: '',
      selectVisitingType: '',
      visitingTypeColumns: [],
      visitingDate: '',
      showVisitingDatePicker: false,
      visitingReason: '',
      visitingResult: '',
      relevanceClueId: '',
      relevanceClue: {},
      // 关联商机
      showCluePicker: false,
      clubeSearchkey: '',
      clueColumns: [],
      customFieldName: { text: 'title', value: 'id' },
      customerName: '',
      customerAddress: '',
      linkman: '',
      linkmanPhone: '',
      internalVisitor: '',
      otherVisitor: '',
      // 区域
      areaResult: '',
      areaCode: [],
      showArea: false,
      cityName: '',
      visitingFile: [],
      visitingUploadFile: [],
      remark: '',
      waterMarkDisabled: false // 添加水印等待
    })

    onMounted(async () => {
      // getSign()
      initDictionary('crm_visit_type')
      getRelevanceClueList()
      state.visitingDate = formatterDate(new Date())
      if (route.query.id) {
        document.title = '编辑拜访'
        state.visitingId = route.query.id
        setTimeout(() => {
          getVisitingDetail()
        })
      }
      // ww.onHistoryBack(() => {
      //   router.back()
      //   return false
      // })
    })

    const initDictionary = (code) => {
      getDictionary({ code }).then((res) => {
        const newDic = transOption(res)
        console.log('newDic::::', newDic)
        if (code === 'crm_visit_type') {
          state.visitingTypeColumns = newDic
          if (!state.visitingId) {
            newDic.forEach((item) => {
              if (item.value === 'PB') {
                state.selectVisitingType = item.value
              }
            })
          }
        }
      })
    }

    const transOption = (data) => {
      const newDate = []
      data.map((item) => {
        const obj = {
          text: item.dictValue,
          value: item.dictKey
        }
        newDate.push(obj)
      })
      return newDate
    }
    const handleOpenCluePicker = () => {
      state.showCluePicker = true
      state.clubeSearchkey = ''
      state.relevanceClueId = state.relevanceClue.id
      getRelevanceClueList()
    }
    const getRelevanceClueList = () => {
      const { id } = JSON.parse(localStorage.getItem('userInfo'))
      let params = {
        ownerUserId: id,
        title: state.clubeSearchkey,
        current: 1,
        size: 10000
      }
      getRelevanceClue(params).then((res) => {
        state.clueColumns = res.records
      })
    }
    const onSearch = () => {
      getRelevanceClueList()
    }

    const getVisitingDetail = () => {
      getBusinessVisiting(state.visitingId).then((res) => {
        console.log('.......', res)
        state.selectVisitingType = res.visitType
        state.visitingDate = res.visitTime
        state.visitingReason = res.visitReason
        state.visitingResult = res.visitResult
        state.relevanceClue.id = res.businessId
        state.relevanceClue.sn = res.businessSn
        state.relevanceClue.title = res.businessName
        state.customerName = res.customerName
        state.customerAddress = res.address
        state.linkman = res.contactsName
        state.linkmanPhone = res.phoneNumber
        state.internalVisitor = res.escortUser
        state.otherVisitor = res.otherEscortUser
        state.areaResult = res.region
        state.cityName = res.city
        if (res?.enclosureList?.length) {
          res.enclosureList.forEach((item) => {
            state.visitingFile.push({
              url: item.value
            })
          })
          state.visitingUploadFile = res.enclosureList
        }
        console.log('visitingUploadFile', state.visitingUploadFile)
        state.remark = res.remark
      })
    }

    const onConfirmVisitingDate = (value) => {
      state.visitingDate = formatterDate(value)
      state.showVisitingDatePicker = false
    }

    const onConfirmClue = (val) => {
      if (val) {
        const value = state.clueColumns.filter((i) => {
          return i.id == val
        })[0]
        console.log('onConfirmClue', value)
        state.relevanceClue = value
        state.customerName = value.customerName
        state.customerAddress = value.address + value.detailAddress
        state.linkman = value.contactsName
        state.linkmanPhone = value.phoneNumber
      }
      state.showCluePicker = false
    }

    const getLocation = () => {
      console.log('点击定位')
    }

    const onConfirmArea = (value) => {
      console.log('选择省市区', value)
      let city = ''
      let cityCode = []
      value.forEach((item) => {
        city += item.name
        cityCode.push(item.code)
      })
      state.areaResult = city
      state.areaCode = cityCode
      state.showArea = false
    }

    const deleteVisitingFile = (indexData) => {
      state.visitingFile.splice(indexData.index, 1)
      state.visitingUploadFile.splice(indexData.index, 1)
    }

    const beforeRead = () => {
      state.waterMarkDisabled = true
    }
    const afterRead = (file) => {
      // 此时可以自行将文件上传至服务器
      console.log('###', file)
      const formData = new FormData()
      formData.append('file', file.file)

      // 示例使用 axios 进行文件上传
      uploadFile(formData)
    }

    const uploadFile = (formData) => {
      // 使用你的上传接口地址替换以下 URL
      const url = 'web-service/oss/endpoint/put-file'
      // 这里使用 axios 作为请求示例
      request
        .post(url, formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          onUploadProgress: (progressEvent) => {
            // 这里可以获取上传进度
            console.log(progressEvent)
          }
        })
        .then((response) => {
          // 上传成功处理
          console.log('visitingUploadFile::::', state.visitingUploadFile)
          // console.log("visitingFile::::", state.visitingFile);
          state.visitingFile.push({
            url: response.link
          })
          state.visitingUploadFile.push({
            label: response.originalName,
            value: response.link
          })
          state.waterMarkDisabled = false
        })
        .catch((error) => {
          // 上传失败处理
          console.error(error)
          state.waterMarkDisabled = false
        })
    }

    const onSubmit = () => {
      if (state.waterMarkDisabled) {
        Toast('正在生成水印图片！')
        return
      }
      const { realName, deptName, id, deptId, phone } = JSON.parse(localStorage.getItem('userInfo'))

      let params = {
        visitType: state.selectVisitingType,
        visitTime: state.visitingDate,
        visitReason: state.visitingReason,
        visitResult: state.visitingResult,
        businessSn: state.relevanceClue.sn,
        businessId: state.relevanceClue.id,
        customerName: state.customerName,
        address: state.customerAddress,
        contactsName: state.linkman,
        phoneNumber: state.linkmanPhone,
        escortUser: state.internalVisitor,
        otherEscortUser: state.otherVisitor,
        region: state.areaResult,
        city: state.cityName,
        enclosureList: state.visitingUploadFile,
        remark: state.remark,
        ownerUserExt: realName + deptName,
        ownerUserId: id,
        ownerUser: realName,
        ownerDeptId: deptId,
        ownerDeptName: deptName,
        ownerPhoneNumber: phone
      }
      console.log('提交', params)
      if (state.visitingId) {
        params.id = state.visitingId
      }
      addBusinessVisiting(params).then((res) => {
        Toast.success(`${state.visitingId ? '编辑' : '新增'}拜访成功！`)
        setTimeout(() => {
          router.back()
        }, 500)
      })
    }

    return {
      areaList,
      ...toRefs(state),
      onSubmit,
      formatter,
      onConfirmVisitingDate,
      handleOpenCluePicker,
      onConfirmClue,
      onSearch,
      getLocation,
      onConfirmArea,
      beforeRead,
      afterRead,
      deleteVisitingFile
    }
  }
}
</script>

<style scoped lang="less">
.addVisiting-container {
  .addVisiting-save {
    display: flex;
    justify-content: flex-end;
    margin: 20px;
  }
}
</style>
